package com.toommi.refuse.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.toommi.refuse.common.enums.WorkStatusEnum;
import com.toommi.refuse.common.util.DateUtil;
import com.toommi.refuse.entity.*;
import com.toommi.refuse.enums.AppUserExceptionEnum;
import com.toommi.refuse.enums.CommonStatusExceptionEnum;
import com.toommi.refuse.enums.RefuseTypeExceptionEnum;
import com.toommi.refuse.exception.AppUserException;
import com.toommi.refuse.exception.CommonStatusException;
import com.toommi.refuse.exception.RefuseTypeException;
import com.toommi.refuse.exception.WechatUserException;
import com.toommi.refuse.mapper.*;
import com.toommi.refuse.service.LargeAppointmeService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author yangg
 * @since 2019-07-26 11:33
 */
@Service
@AllArgsConstructor
public class LargeAppointmeServiceImpl implements LargeAppointmeService {


    private LargeAppointmeMapper appointmeMapper;

    private WechatUserMapper wechatUserMapper;

    private RefuseTypeMapper refuseTypeMapper;

    private AppUserMapper appUserMapper;

    private WechatUserHouseholdMapper wechatUserHouseholdMapper;

    private NeighbourhoodMapper neighbourhoodMapper;

    private HouseholdMapper householdMapper;

    private BuildingMapper buildingMapper;

    private AreaMapper areaMapper;


    @Override
    public void addAppointme(HttpServletRequest request) throws WechatUserException, RefuseTypeException {
        String uid = request.getParameter("uid");
        String uname = request.getParameter("uname");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String content = request.getParameter("content");
        String date = request.getParameter("date");
        String type = request.getParameter("type");
        //直接吧输入放入表
        Map<String, Object> par = new HashMap<>();
        par.put("uid", uid);
        par.put("uname", uname);
        par.put("phone", phone);
        par.put("address", address);
        par.put("content", content);
        par.put("date", date);
        StringBuffer buffer = new StringBuffer();
        //再把类型区分
        String[] arg = type.split(",");
        for (int i = 0; i < arg.length; i++) {
            String typename = "无";
            typename = refuseTypeMapper.findOneById(Integer.parseInt(arg[i])).getName();
//            if ("1".equals(arg[i])) {
//                typename = "纸板";
//            } else if ("2".equals(arg[i])) {
//                typename = "塑料";
//            } else if ("3".equals(arg[i])) {
//                typename = "泡沫";
//            }
            if (i == arg.length - 1) {
                buffer.append(typename);
            } else {
                buffer.append(typename + ",");
            }
        }
        par.put("typecontent", buffer.toString());
        par.put("ordercode", UUID.randomUUID().toString().replaceAll("\\-", ""));
        appointmeMapper.addAppointme(par);
        for (int i = 0; i < arg.length; i++) {
            String typename = "无";
            /*if ("1".equals(arg[i])) {
                typename = "纸板";
            } else if ("2".equals(arg[i])) {
                typename = "塑料";
            } else if ("3".equals(arg[i])) {
                typename = "泡沫";
            }*/
            typename = refuseTypeMapper.findOneById(Integer.parseInt(arg[i])).getName();
            appointmeMapper.insertType(String.valueOf(par.get("id")), typename, arg[i]);
        }
    }

    @Override
    public void deleteAppointme(long id) {
        appointmeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void updateAppointme(LargeAppointme appointme) throws RefuseTypeException, AppUserException, CommonStatusException {
        //允许更新状态，及责任人
        LargeAppointme largeAppointme = appointmeMapper.selectByPrimaryKey(appointme.getId());
        if (largeAppointme == null) {
            throw new RefuseTypeException(RefuseTypeExceptionEnum.INVALID_APPOINTME_NULL);
        }
        if (appointme.getAppUserId() != null && appointme.getAppUserId() > 0) {
            //更新责任人
            AppUser appUser = appUserMapper.selectByPrimaryKey(appointme.getAppUserId());
            if (appUser == null) {
                throw new AppUserException(AppUserExceptionEnum.INVALID_USER_NULL);
            }
            largeAppointme.setAppUserName(appUser.getName());
            largeAppointme.setAppUserPhone(appUser.getPhone());
            largeAppointme.setAppUserId(appointme.getAppUserId());

        }

        if (!WorkStatusEnum.hasValue(appointme.getStatus())) {
            throw new CommonStatusException(CommonStatusExceptionEnum.INVALID_LARGE_APPOINTME_STATUS);
        }

        largeAppointme.setStatus(appointme.getStatus());
        largeAppointme.setStatusNote(WorkStatusEnum.getByCode(appointme.getStatus()).getNote());
        largeAppointme.setUpdateTime(System.currentTimeMillis());


        appointmeMapper.updateByPrimaryKey(largeAppointme);
    }

    @Override
    public PageInfo<LargeAppointme> findAppoints(int pageNum, int pageSize, long wechatUserId, long appUserId, int status,
                                                 String districtId, String streetId, long neighbourhoodId,
                                                 long startTime, long endTime) {

        PageHelper.startPage(pageNum, pageSize);

        LargeAppointmeExample example = new LargeAppointmeExample();
        example.setOrderByClause(" id desc");
        LargeAppointmeExample.Criteria criteria = example.createCriteria();
        //按提交人过滤查询
        if (wechatUserId > 0) {
            criteria.andWechatUserIdEqualTo(wechatUserId);
        }
        //按处理人过滤查询
        if (appUserId > 0) {
            criteria.andAppUserIdEqualTo(appUserId);
        }
        //按状态过滤查询
        if (status >= 0) {
            criteria.andStatusEqualTo(status);
        }
        //按行政区划过滤查询
        if (StringUtils.isNotEmpty(districtId)) {
            criteria.andDistrictIdEqualTo(districtId);
        }
        //按街道过滤查询
        if (StringUtils.isNotEmpty(streetId)) {
            criteria.andStreetIdEqualTo(streetId);
        }
        //按小区过滤查询
        if (neighbourhoodId > 0) {
            criteria.andNeighbourhoodIdEqualTo(neighbourhoodId);
        }
        //按提交时间过滤查询
        if (startTime > 0) {
            criteria.andCreateTimeGreaterThanOrEqualTo(startTime);
        }
        if (endTime > 0) {
            criteria.andCreateTimeLessThanOrEqualTo(endTime);
        }

        List<LargeAppointme> largeAppointmes = appointmeMapper.selectByExample(example);

        return new PageInfo<>(largeAppointmes);
    }

    @Override
    public LargeAppointme findDetail(long id) throws RefuseTypeException {

        LargeAppointme appointme = appointmeMapper.selectByPrimaryKey(id);

        if (appointme == null) {
            throw new RefuseTypeException(RefuseTypeExceptionEnum.INVALID_APPOINTME_NULL);
        }

        return appointme;
    }

    @Override
    public Map<String, Object> deleteAppointTest(long id) {
        return appointmeMapper.deleteAppointTest(id);
    }

    /**
     * 获取订单列表
     *
     * @param request
     * @return
     */
    @Override
    public Object orderlist(HttpServletRequest request) throws RefuseTypeException, AppUserException, CommonStatusException {
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        String uid = request.getParameter("uid");
        String appid = request.getParameter("appid");
        String status = request.getParameter("status");
        PageHelper.startPage(Integer.valueOf(pageNum), Integer.valueOf(pageSize));
        List<Map<String, Object>> largeAppointmes = appointmeMapper.orderlist(uid, appid, status);
        return new PageInfo<>(largeAppointmes).getList();
    }

    /**
     * 获取订单详情
     *
     * @param request
     * @return
     * @throws RefuseTypeException
     * @throws AppUserException
     * @throws CommonStatusException
     */
    @Override
    public Object orderinfo(HttpServletRequest request) throws RefuseTypeException, AppUserException, CommonStatusException {
        String id = request.getParameter("id");
        Map<String, Object> orderinfo = appointmeMapper.orderinfo(id);
        //再获取类型
        List<Map<String, Object>> typelist = appointmeMapper.getTypelist(id);
        orderinfo.put("typelist", typelist);
        return orderinfo;
    }

    /**
     * 回收端结算
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = RefuseTypeException.class)
    public void Settlement(Ordertableinfo ordertableinfo) throws RefuseTypeException {
        String date = DateUtil.formatTimestampToString(System.currentTimeMillis(), DateUtil.DATE_FORMATE_YM);
        //先更新订单表
        appointmeMapper.updateOrder(ordertableinfo);
        //再更新类型表
        List<Map<String, Object>> list = ordertableinfo.getList();
        appointmeMapper.Settlement(list, ordertableinfo.getId());
        //这里还需要添加用户的余额和积分
        Map<String, Object> orderinfo = appointmeMapper.getOrderInfo(ordertableinfo.getId());

        //计算积分(1斤=1分，重量向下取整)
        double v = Math.floor(Double.parseDouble(ordertableinfo.getAllweight()));
        String jf = String.valueOf(v * 2);
        appointmeMapper.updateUser(String.valueOf(orderinfo.get("uid")), ordertableinfo.getMoney(), jf);
        //判断当月这个用户是否有数据，有的话就更新
        Map<String, Object> map = appointmeMapper.getAPPMoney(ordertableinfo.getAppid(), date);
        if (map != null) {
            BigDecimal money = new BigDecimal(ordertableinfo.getMoney()).add(new BigDecimal(String.valueOf(map.get("money"))));
            map.put("money", money);
            appointmeMapper.updateMoney(map);
        } else {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("money", ordertableinfo.getMoney());
            map1.put("date", date);
            map1.put("app_user_id", ordertableinfo.getAppid());
            appointmeMapper.insertMoney(map1);
        }


    }

    /**
     * 更新状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updatestatus(String id, String status) throws RefuseTypeException {
        appointmeMapper.updatestatus(id, status);

    }

    /**
     * 获取APP端用户信息
     *
     * @param request
     * @return
     * @throws RefuseTypeException
     */
    @Override
    public Object getappinfo(HttpServletRequest request) throws RefuseTypeException {
        String id = request.getParameter("id");
        String date = DateUtil.formatTimestampToString(System.currentTimeMillis(), DateUtil.DATE_FORMATE_YM);
        return appointmeMapper.getappinfo(id, date);
    }

    /**
     * 获取用户端用户信息
     *
     * @param request
     * @return
     * @throws RefuseTypeException
     */
    @Override
    public Object getuserinfo(HttpServletRequest request) throws RefuseTypeException {
        String id = request.getParameter("id");

        return appointmeMapper.getuserinfo(id);
    }

    /**
     * 修改用户信息
     *
     * @param request
     * @return
     */
    @Override
    public void updateuserinfo(HttpServletRequest request) throws RefuseTypeException {
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String phone = request.getParameter("phone");
        String comaddress = request.getParameter("comaddress");
        appointmeMapper.updateuserinfo(id, username, phone, comaddress);
    }

    /**
     * 功能描述: 回收端根据id修改订单废品类型描述
     *
     * @param: [request]
     * @return: void
     * @auther: HuangBo
     * @date: 2019/9/17 0017 下午 15:42
     */
    @Override
    public void updateTypeContentById(String id, String type) throws RefuseTypeException {
        if (StringUtils.isBlank(type)) {
            return;
        }
        StringBuffer typecontent = new StringBuffer();
        //根据id获取订单详情
        Map<String, Object> orderInfo = appointmeMapper.getOrderInfo(id);
        //根据订单id删除订单中的废品种类
        appointmeMapper.deleteTypeByOid(id);
        //将type转换成垃圾种类ids
        String[] ids = type.split(",");
        String typeName = "";
        //拼接订单新的typecontent字段
        for (int i = 0; i < ids.length; i++) {
            RefuseType refuseType = refuseTypeMapper.findOneById(Integer.parseInt(ids[i]));
            typeName = refuseType.getName();
            if (i == ids.length - 1) {
                typecontent.append(typeName);
            } else {
                typecontent.append(typeName + ",");
            }
            appointmeMapper.insertType(id, typeName, ids[i]);
        }
        //再更新订单中的废品类型描述
        appointmeMapper.updateTypecontentByid(typecontent.toString(), id);
    }

    /***
     * 功能描述: 获取上一次填写地址
     * @param: [request]
     * @return: java.lang.String
     * @auther: HuangBo
     * @date: 2019/9/18 0018 下午 12:07
     */
    @Override
    public Map<String, Object> getLastPhoneAndAddr(HttpServletRequest request) {
        String id = request.getParameter("uid");
        Map<String, Object> res = new HashMap<>();
        res = appointmeMapper.getLastOrderPhoneAndAddr(id);
        return res;
    }

}
